package com.itic.appbase.applications.sys.code.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.code.persistence.model.Code;
import com.itic.appbase.applications.sys.code.persistence.model.CodeDetail;
import com.itic.appbase.applications.sys.code.persistence.model.CodeDetailExample;
import com.itic.appbase.applications.sys.code.persistence.model.CodeDetailExample.Criteria;
import com.itic.appbase.applications.sys.code.service.CodeDetailService;
import com.itic.appbase.applications.sys.code.service.CodeService;
import com.itic.appbase.applications.sys.code.vo.CodeVo;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;

/**
 * 代码详情表管理
 * <p>
 * Company: itic
 * </p>
 * 
 * @author: shijun
 * @date: 2015年5月15日 上午10:40:43
 * @version: V1.0
 */
@Controller
@RequestMapping(value = "/sys/codeDetail")
public class CodeDetailController
        extends BaseController {
    @Autowired
    private CodeDetailService codeDetailService;

    @Autowired
    private CodeService codeService;

    /**
     * 进入代码详情主页面
     * 
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/initDetatil")
    public String initDetail(String id, Model model) {
        CodeVo codeVo = new CodeVo();
        codeVo = getCodeVo(id, codeVo);
        model.addAttribute(codeVo);
        return "sys/code/codeDetailMain";
    }

    /**
     * 代码详情右侧iframe，详情列表
     * 
     * @return
     */
    @RequestMapping(value = "/init")
    public String init(String parentId, Model model) {
        CodeVo codeVo = new CodeVo();
        codeVo = getCodeVo(parentId, codeVo);
        model.addAttribute(codeVo);
        return "sys/code/codeDetailList";
    }

    /**
     * 新增页面
     * 
     * @return
     */
    @RequestMapping(value = "/initAdd")
    public String initAdd() {
        return "sys/code/codeDetailAdd";
    }

    /**
     * 编辑页面
     * 
     * @return
     */
    @RequestMapping(value = "/initEdit")
    public String initEdit(String id, Model model) {
        if (StringHelper.isNotBlank(id)) {
            CodeDetail codeDetail = codeDetailService.get(id);
            model.addAttribute(codeDetail);
        } else {
            throw new ParameterErrorException();
        }

        return "sys/code/codeDetailEdit";
    }

    /**
     * 数据列表展示
     * 
     * @param codeDetail
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(CodeDetail codeDetail, HttpServletRequest request) {
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 参数处理
        CodeDetailExample codeDetailExample = new CodeDetailExample();
        // 封装分页参数
        codeDetailExample = this.handlePageQuery(request, codeDetailExample);
        // 封装查询条件
        codeDetailExample = queryCondition(codeDetail, codeDetailExample);
        // 获取数据
        List<CodeDetail> roleList = codeDetailService.list(codeDetailExample);
        // 获取数据总数
        int totalNum = codeDetailService.count(codeDetailExample);
        // 数据返回处理
        resultMap.put(IticConst.DATA, roleList);
        resultMap.put(IticConst.TOTAL_RECORDS, totalNum); // 总记录
        resultMap.put(IticConst.DISPLAY_RECORDS, totalNum);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        return resultMap;
    }

    /**
     * 左侧树数据展示
     * 
     * @param parentId
     * @param request
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    @RequestMapping(value = "/dataTree")
    @ResponseBody
    public Map<String, Object> dataTree(String parentId) {
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 获取数据
        List<CodeDetail> codeList = null;
        Code code = codeService.get(parentId);// 获取代码表原数据信息
        if (null != code) {
            CodeDetail codeDetail = new CodeDetail();
            // 将代码表中的code，做为详情表代码树的根节点
            codeDetail = (CodeDetail) ValueHelper.model2vo(code, codeDetail);
            if (null != codeDetail) {
                codeList = codeDetailService.selectCodeDetail(parentId);// 获取代码详情信息
                codeList.add(codeDetail);// 添加根节点
            }
        }
        // 数据返回处理
        resultMap.put(IticConst.DATA, codeList);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        return resultMap;
    }

    /**
     * 异步刷新左侧树数据
     * 
     * @param parentId
     * @param request
     * @return
     */
    @RequestMapping(value = "/asyncDataTree")
    @ResponseBody
    public List<CodeDetail> asyncDataTree(String parentId) {
        // 获取数据
        return codeDetailService.selectCodeDetail(parentId);// 获取代码详情信息
    }

    /**
     * 代码表新增
     * 
     * @param codeDetail
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Map<String, Object> add(CodeDetail codeDetail) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (null != codeDetail) {
            result = codeDetailService.add(codeDetail);

        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 代码表修改
     * 
     * @param codeDetail
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(CodeDetail codeDetail) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (null != codeDetail) {
            result = codeDetailService.edit(codeDetail);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 删除代码
     * 
     * @param ids
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(String ids, String type) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (StringHelper.isNotBlank(ids)) {
            List<String> idList = Arrays.asList(ids.trim().split(","));// codeIds
            CodeDetailExample codeDetailExample = new CodeDetailExample();
            codeDetailExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andIdIn(idList);
            CodeDetail codeDetail = new CodeDetail();
            codeDetail.setUpdateTime(new Date());
            codeDetail.setIsEffective(DBConst.FALSE);
            codeDetail.setType(type);
            result = codeDetailService.deleteCodeDetail(codeDetail, codeDetailExample, idList);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 校验代码详情表code是否重复
     * 
     * @param codeDetail
     * @return
     */
    @RequestMapping(value = "/checkCodeDetailExist")
    @ResponseBody
    public Map<String, Object> checkCodeDetailExist(CodeDetail codeDetail) {
        // type ：T_DM_SEX 和 code : 0
        Map<String, Object> resultMap = new HashMap<String, Object>();
        CodeDetailExample codeDetailExample = new CodeDetailExample();
        Criteria criteria = codeDetailExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        // 封装查询条件
        if (null != codeDetail) {
            if (StringHelper.isNotBlank(codeDetail.getType())) {// 代码表类别
                criteria.andTypeEqualTo(codeDetail.getType());
            }
            if (StringHelper.isNotBlank(codeDetail.getCode())) {// 代码表code
                criteria.andCodeEqualTo(codeDetail.getCode());
            }
            if (StringHelper.isNotBlank(codeDetail.getId())) {// 自身id
                criteria.andIdNotEqualTo(codeDetail.getId());
            }
            // 获取数据
            List<CodeDetail> codeDetailList = codeDetailService.list(codeDetailExample);

            if (null != codeDetailList && !codeDetailList.isEmpty()) {
                resultMap.put(IticConst.RESULT, ResponseCode.EXIST.getCode());// 代码详情表中代码已存在
            } else {
                resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());// 代码表代码可用
            }
        } else {
            resultMap.put(IticConst.RESULT, ResponseCode.PARAM_INVALID.getCode());// 参数不合法
        }
        return resultMap;
    }

    /**
     * 封装查询条件
     * 
     * @param codeDetail
     * @param codeExample
     * @return CodeDetailExample
     */
    private CodeDetailExample queryCondition(CodeDetail codeDetail, CodeDetailExample codeDetailExample) {
        codeDetailExample.setOrderByClause("ORDER_NO asc");
        // 封装查询条件
        Criteria criteria = codeDetailExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        if (null != codeDetail && StringHelper.isNotBlank(codeDetail.getParentId())) {
            criteria.andParentIdEqualTo(codeDetail.getParentId());
        }
        return codeDetailExample;
    }

    /**
     * 代码表或者代码详情表转vo
     * 
     * @param id
     * @param codeVo
     * @return
     */
    private CodeVo getCodeVo(String id, CodeVo codeVo) {
        Code code = codeService.get(id);
        if (null == code) {
            CodeDetail codeDetail = codeDetailService.get(id);
            if (null != codeDetail) {
                codeVo.setCode(codeDetail.getCode());// 子类代码表父类代码
                codeVo.setType(codeDetail.getType());// 子类代码表父类类型
                codeVo.setId(codeDetail.getId());// 子类代码表父类id
                codeVo.setName(codeDetail.getName());// 子类代码表父类名称
            }
        } else {
            codeVo.setCode(code.getCode());// 子类代码表父类代码
            codeVo.setType(code.getCode());// 子类代码表父类类型
            codeVo.setId(code.getId());// 子类代码表父类id
            codeVo.setName(code.getName());// 子类代码表父类名称
        }
        return codeVo;
    }
}